package com.tsinghuabigdata.edu.ddmath.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tsinghuabigdata.edu.ddmath.MVPModel.MyStudyModel;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.activity.MainActivity;
import com.tsinghuabigdata.edu.ddmath.adapter.UploadAdatper;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.MyCourse;
import com.tsinghuabigdata.edu.ddmath.bean.Records;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.LocalWorkManager;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.WaitUploadActivity;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.XBookCameraActivity;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.bean.WaitWorkBean;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.DataUtils;
import com.tsinghuabigdata.edu.ddmath.util.DensityUtils;
import com.tsinghuabigdata.edu.ddmath.util.ToastUtils;
import com.tsinghuabigdata.edu.ddmath.util.WindowUtils;
import com.tsinghuabigdata.edu.ddmath.view.CoursePager;

import java.util.ArrayList;
import java.util.List;

/**
 * 学校作业
 * Created by Administrator on 2017/3/14.
 */

public class SchoolWorkFragment extends Fragment implements View.OnClickListener, PullToRefreshBase.OnRefreshListener {

    private static final String TAG = "SchoolWorkFragment";

    private PullToRefreshListView mLvTakePhoto;
    private CoursePager           mCoursePager;
    private View                  mViewToUpload;
    private LinearLayout          mLlToUpload;
    private TextView              mTvToUpload;
    private ImageView             mIvCamera;

    private Context      mContext;
    private MainActivity mainActivity;
    private MyStudyModel  mMyStudyModel = new MyStudyModel();
    private List<Records> mList         = new ArrayList<Records>();
    private UploadAdatper mAdatper;

    private boolean toUploadShow;
    private int     mToUploadsize;
    private String  mLoginName;

    private int pageNum  = 1;
    private int pageSize = 20;
    private String accessToken;
    private String studentId;
    private String classId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i("burning", "SchoolWorkFragment onCreateView");
        View root = inflater.inflate(R.layout.fragment_school_work, container, false);
        initView(root);
        initData();
        return root;
    }

    private void initView(View root) {
        mContext = getActivity();
        mainActivity = (MainActivity) getActivity();

        mLvTakePhoto = (PullToRefreshListView) root.findViewById(R.id.lv_take_photo);
        mIvCamera = (ImageView) root.findViewById(R.id.iv_camera);
        mCoursePager = (CoursePager) root.findViewById(R.id.coursePager);
        ILoadingLayout loadingLayout = mLvTakePhoto.getLoadingLayoutProxy(true, false);
        loadingLayout.setRefreshingLabel("刷新中...");
        loadingLayout.setLoadingDrawable(getResources().getDrawable(R.drawable.refresh_loading_anim));

        mCoursePager.setTargetView(mLvTakePhoto);
        mLvTakePhoto.setVisibility(View.VISIBLE);
        mList.clear();
        mAdatper = new UploadAdatper(getActivity(), mList);
        mLvTakePhoto.setAdapter(mAdatper);
        mCoursePager.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCoursePager.showLoading();
                queryPhoto(true);
            }
        });
        mLvTakePhoto.setOnRefreshListener(this);
        mIvCamera.setOnClickListener(this);

        mViewToUpload = getActivity().getLayoutInflater().inflate(R.layout.view_to_upload, null);
        mLlToUpload = (LinearLayout) mViewToUpload.findViewById(R.id.ll_to_upload);
        mTvToUpload = (TextView) mViewToUpload.findViewById(R.id.tv_to_upload);
        ViewGroup.LayoutParams layoutParams = mLlToUpload.getLayoutParams();
        int width = WindowUtils.getScreenWidth(getActivity()) - DensityUtils.dp2px(getActivity(), 435);
        layoutParams.width = width / 5;
        layoutParams.height = width * 109 / 120 / 5;
        mLlToUpload.setLayoutParams(layoutParams);
        mLlToUpload.setOnClickListener(this);

    }

    private void initData() {
        IntentFilter intentFilter = new IntentFilter(AppConst.ACTION_UPLOAD_SUCCESS);
        mainActivity.registerReceiver(new UploadSuccessReceiver(), intentFilter);
        createLoginInfo();
    }

    //查询登录信息
    private void createLoginInfo() {
        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if (loginInfo != null) {
            accessToken = loginInfo.getAccessToken();
            mLoginName = loginInfo.getLoginName();
            Log.i(TAG, "accessToken=" + accessToken + "mLoginName=" + mLoginName);
            UserDetailinfo detailinfo = AccountUtils.getUserdetailInfo();
            if (detailinfo == null || detailinfo.getJoinedClassInfoList() == null || detailinfo.getJoinedClassInfoList().size() == 0) {

            } else {
                studentId = detailinfo.getJoinedClassInfoList().get(0).getClassId();
                classId = detailinfo.getStudentId();
                queryPhoto(true);
                queryUploadSize();
                Log.i(TAG, "classId=" + classId + "studentId=" + studentId);
            }
        }
    }

    //查询拍照上传作业列表
    public void queryPhoto(final boolean first) {
        mMyStudyModel.queryMyCourse(accessToken, studentId, classId, pageNum, pageSize, new RequestListener<List<MyCourse>>() {
            @Override
            public void onSuccess(List<MyCourse> resList) {
                Log.i(TAG, "queryPhoto onSuccess");
                if (resList == null || resList.size() == 0) {
                    if (mToUploadsize > 0) {
                        mCoursePager.showTarget();
                    } else {
                        mCoursePager.showEmpty();
                    }
                    return;
                }
                Log.i(TAG, "resList.size()=" + resList.size());
                List<Records> recordsList = DataUtils.select(resList);
                mList.clear();
                mList.addAll(recordsList);
                if (mAdatper == null) {
                    mAdatper = new UploadAdatper(getActivity(), mList);
                    mLvTakePhoto.setAdapter(mAdatper);
                } else {
                    mAdatper.notifyDataSetChanged();
                }
                if (resList.size() < pageSize) {
                    Log.i(TAG, "PULL_FROM_START");
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    Log.i(TAG, "BOTH");
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.BOTH);
                }
                mCoursePager.showTarget();
            }

            @Override
            public void onFail(HttpResponse<List<MyCourse>> response, Exception ex) {
                Log.i(TAG, "queryPhoto onFail");
                if (first) {
                    mCoursePager.showFault();
                } else {
                    ToastUtils.showShort(getActivity(), R.string.server_error);
                }

            }
        });
    }

    //查询未上传照片数量
    public void queryUploadSize() {
        LocalWorkManager localWorkManager = LocalWorkManager.getLocalWorkManager(getActivity(), mLoginName);
        if (localWorkManager == null)      //TODO
            return;

        mToUploadsize = localWorkManager.getWaitWorkList().size();
        Log.i(TAG, "mLoginName=" + mLoginName + "size=" + mToUploadsize);
        if (mToUploadsize > 0) {
            showUploadView(true);
            mTvToUpload.setText("已有" + mToUploadsize + "组图片，请尽快上传");
        } else {
            showUploadView(false);
        }
    }

    //根据未上传照片数量决定是否展示未上传照片头布局
    private void showUploadView(boolean show) {
        if (show == toUploadShow) {
            return;
        }
        if (show) {
            mLvTakePhoto.getRefreshableView().addHeaderView(mViewToUpload);
        } else {
            mLvTakePhoto.getRefreshableView().removeHeaderView(mViewToUpload);
        }
        toUploadShow = show;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_camera: {
                mToUploadsize = 0;
                LocalWorkManager localWorkManager = LocalWorkManager.getLocalWorkManager();
                if (localWorkManager != null) {
                    WaitWorkBean workBean = localWorkManager.getNotUploadWaitWork();
                    if (workBean != null) {
                        mToUploadsize = workBean.getImageList().size();
                    }
                }
                if (mToUploadsize > 12) {
                    ToastUtils.showToastCenter(getActivity(), "不能继续拍摄，\n未上传图片最多12张哦~");
                } else {
                    Intent intent = new Intent(getActivity(), XBookCameraActivity.class);
                    startActivity(intent);
                }
            }
            break;
            case R.id.ll_to_upload: {
                Intent intent = new Intent(getActivity(), WaitUploadActivity.class);
                startActivity(intent);
            }
            break;
        }
    }

    @Override
    public void onRefresh(PullToRefreshBase pullToRefreshBase) {
        if (pullToRefreshBase.isHeaderShown()) {
            refreshData();
        } else {
            getMoreData();
        }
    }

    //加载更多——拍照上传作业列表
    private void getMoreData() {
        pageSize += 20;
        mMyStudyModel.queryMyCourse(accessToken, studentId, classId, pageNum, pageSize, new RequestListener<List<MyCourse>>() {
            @Override
            public void onSuccess(List<MyCourse> resList) {
                Log.i(TAG, "resList.size()=" + resList.size());
                if (resList == null || resList.size() == 0) {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    mLvTakePhoto.onRefreshComplete();
                    return;
                }
                List<Records> recordsList = DataUtils.select(resList);
                mList.clear();
                mList.addAll(recordsList);
                mAdatper.notifyDataSetChanged();
                if (resList.size() < pageSize) {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.BOTH);
                }
                mLvTakePhoto.onRefreshComplete();
            }

            @Override
            public void onFail(HttpResponse<List<MyCourse>> response, Exception ex) {
                ToastUtils.showShort(getActivity(), R.string.server_error);
                mLvTakePhoto.onRefreshComplete();
            }
        });
    }

    //刷新——拍照上传作业列表
    private void refreshData() {
        pageSize = 20;
        mMyStudyModel.queryMyCourse(accessToken, studentId, classId, pageNum, pageSize, new RequestListener<List<MyCourse>>() {
            @Override
            public void onSuccess(List<MyCourse> resList) {
                Log.i(TAG, "resList.size()=" + resList.size());
                if (resList == null || resList.size() == 0) {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    mLvTakePhoto.onRefreshComplete();
                    return;
                }
                List<Records> recordsList = DataUtils.select(resList);
                mList.clear();
                mList.addAll(recordsList);
                mAdatper.notifyDataSetChanged();
                if (resList.size() < pageSize) {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.BOTH);
                }
                mLvTakePhoto.onRefreshComplete();
            }

            @Override
            public void onFail(HttpResponse<List<MyCourse>> response, Exception ex) {
                ToastUtils.showShort(getActivity(), R.string.server_error);
                mLvTakePhoto.onRefreshComplete();
            }
        });
    }


    /**
     * 图片上传成功广播接收者
     */
    class UploadSuccessReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (AppConst.ACTION_UPLOAD_SUCCESS.equals(intent.getAction())) {
                Log.i(TAG, "SchoolWorkFragment UploadSuccessReceiver");
                // 收到广播后 查询拍照上传作业列表、未上传照片数量
                if (!TextUtils.isEmpty(classId) && !TextUtils.isEmpty(studentId)) {
                    queryUploadSize();
                    queryPhoto(false);
                }
            }
        }
    }

    public void setId(String accessToken, String classId, String studentId, String loginName) {
        this.accessToken = accessToken;
        this.classId = classId;
        this.studentId = studentId;
        this.mLoginName = loginName;
    }
}
